/*
 * @Descripttion: 
 * @version: 
 * @Author: 2020-12-16 11:14:48
 * @Date: 2020-09-03 10:40:09
 * @LastEditors: turingchang
 * @LastEditTime: 2020-12-16 11:30:46
 */

const validator = require('./validator');

var number = {};

/**
 * 数字格式化指定位数。四舍五入
 * @param {number} num 数值
 * @param {number} n 位数
 */
number.formatNumber = function (num, n) {
    if (validator.isNull(num)) {
        return 0;
    }
    if (isNaN(num) || (!num && num !== 0)) {
        return 0;
    }
    num = String(num.toFixed(n));
    var re = /(-?\d+)(\d{3})/;
    while (re.test(num)) num = num.replace(re, "$1,$2")
    if (num % 1 == 0) {
        num = num / 1;
    } else {
        if (num.substr(num.length - 1, num.length) == 0) {
            num = num.substr(0, num.length - 1);
        }

        if (num.substr(num.length - 1, num.length) == 0) {
            num = num.substr(0, num.length - 1);
        }

        if (num.substr(num.length - 1, num.length) == 0) {
            num = num.substr(0, num.length - 1);
        }
    }
    return num;
}

/**
 * 数字格式化，不进行四舍五入,位数不够自动补0
 * @param {*} num 数值
 * @param {*} decimals 精确位数
 */
number.format = function (num, decimals) {
    if (validator.isNull(num)) {
        return 0;
    }
    if (isNaN(num) || (!num && num !== 0)) {
        return 0;
    }
    // 默认为保留的小数点后两位
    let dec = decimals ? decimals : 2
    let tempNum = Number(num)
    let pointIndex = String(tempNum).indexOf('.') + 1 // 获取小数点的位置 + 1
    let pointCount = pointIndex ? String(tempNum).length - pointIndex : 0 // 获取小数点后的个数(需要保证有小数位)
    // 源数据为整数或者小数点后面小于decimals位的作补零处理
    if (pointIndex === 0 || pointCount <= dec) {
        let tempNumA = tempNum
        if (pointIndex === 0) {
            tempNumA = `${tempNumA}.`
            for (let index = 0; index < dec - pointCount; index++) {
                tempNumA = `${tempNumA}0`
            }
        } else {
            for (let index = 0; index < dec - pointCount; index++) {
                tempNumA = `${tempNumA}0`
            }
        }
        return tempNumA
    }
    let realVal = ''
    // 截取当前数据到小数点后decimals位
    realVal = `${String(tempNum).split('.')[0]}.${String(tempNum)
        .split('.')[1]
        .substring(0, dec)}`
    // 判断截取之后数据的数值是否为0
    if (realVal == 0) {
        realVal = 0
    }
    return realVal;
}

module.exports = number;